//
//  PerformanceViewController.m
//  A段项目
//
//  Created by 曾凯峻 on 15/1/27.
//  Copyright (c) 2015年 zkj. All rights reserved.
//

#import "PerformanceViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "JokesCellTwo.h"
#import "JokesCellImage.h"
#import "MJRefresh.h"



@interface PerformanceViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UITableView *tableView;
@end

@implementation PerformanceViewController


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.page = 20;
    }
    return self;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 隐藏导航栏
    self.navigationController.navigationBar.translucent = NO;
    // 数组初始化
    self.arr = [NSMutableArray array];
    
    
    [self createView];


    [self headRefreshing];


    
    
}

- (void)headRefreshing
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中,不客气";
}



//加载方法
- (void)headerRereshing
{

    
     //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self.tableView reloadData];
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];

        
        [manager GET:@"http://c.3g.163.com/recommend/getChanListNews?passport=&devId=A0000043C8B68F&size=20&channel=duanzi" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //        NSLog(@"JSON:%@", responseObject);
            [self.arr removeAllObjects];
            
            NSMutableArray *tempArr = [responseObject objectForKey:@"段子"];
            for (NSDictionary *dic in tempArr) {
                // KVC赋值
                Jokes *jokes = [[Jokes alloc] init];
                [jokes setValuesForKeysWithDictionary:dic];
                [self.arr addObject:jokes];
                [jokes release];
                
       

            }
  
            [self.tableView reloadData];
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error:%@", error);
            
            
        }];

        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
    
}


- (void)footerRereshing
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/recommend/getChanListNews?passport=&devId=A0000043C8B68F&size=%ld&channel=duanzi", self.page];
        self.page += 20;
        
        [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //        NSLog(@"JSON:%@", responseObject);
            
            
            
            NSMutableArray *tempArr = [responseObject objectForKey:@"段子"];
            for (NSDictionary *dic in tempArr) {
                // KVC赋值
                Jokes *jokes = [[Jokes alloc] init];
                [jokes setValuesForKeysWithDictionary:dic];
                [self.arr addObject:jokes];
                [jokes release];
                
            }
            //        NSLog(@"arr:%@", self.arr);
            [self.tableView reloadData];
            
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error:%@", error);
            
            
        }];


        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
        
    });
    
    
}




- (void)createView
{
    // 创建tableview
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 110) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // cell分割线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
   
    
    
    // 刷新tableView数据
    [self.tableView reloadData];
    [self.view addSubview:self.tableView];
    [self.tableView release];
}


// tableView必须实现的2个协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

// 每一行要显示的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *str = @"reuse";
    
    JokesCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:str];
    
    if (cell == nil) {
        cell = [[[JokesCellTwo alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str] autorelease];
    }

    cell.cellJokes = [self.arr objectAtIndex:indexPath.row];

    
    static NSString *str1 = @"reuse1";
    JokesCellImage *cellImage = [tableView dequeueReusableCellWithIdentifier:str1];
    if (cellImage == nil) {
        cellImage = [[[JokesCellImage alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str1] autorelease];
    }
    
    cellImage.cellJokes = [self.arr objectAtIndex:indexPath.row];

    
    
    
    if (cellImage.cellJokes.img == nil) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    } else {
        cellImage.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellImage;
    }
    
    
}



// cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
 

    
    Jokes *jokes = [[Jokes alloc] init];
    jokes = [self.arr objectAtIndex:indexPath.row];

    NSString *str = jokes.digest;
    
    
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17]};
    // 参数1: 要给文本显示的范围指定一个宽度
    // 参数2: 系统计算文本高度的方式(以 行 为一个矩形计算)
    // 参数3: 对文本进行设置(主要是字体大小)
    CGRect rect = [str boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    

//    NSLog(@"rect:%f", rect.size.height);
    
    if (jokes.img == nil) {

        return rect.size.height + 90;
    } else {
        return rect.size.height + 90 + (tableView.frame.size.width - 20) / 4 * 3;
    }

    
}




- (void)dealloc
{
    [_jokes release];
    [_arr release];
    [_tableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
